//云开发数据集合中增加以下字段
// {
//   calendarSignData: [],//当月签到的每天
//   signcount: '',//总计签到加1
//   signdata: '',//当天日期 
//   calendarSignDay: '',//当月签到次数
//   signmonth: ''//当月签到次数
// }
//获取应用实例
var app = getApp();
var calendarSignData;
var date;
var calendarSignDay;
const db = wx.cloud.database();
const _ = db.command;
const com = require("../../utils/com.js");
Page({
  data: {
    calendarSignData: [],//当月签到的每天
    signcount: '',//总计签到加1
    signdata: '',//当天日期 
    calendarSignDay: '',//当月签到次数
    signmonth: ''//当月签到次数
  },
  /**
   * 签到
   */
  calendarSign: function () {
    var that = this;
    console.log(calendarSignData);
    var _id = app.globalData.userInfo._id;
    db.collection('userinfo').doc(_id).update({
      data: {
        signdata: _.push([date]),//每月签到日期
        signcount: _.inc(1),//总计签到加1
        signmonth: _.inc(1)//当月签到次数
      },
      success: res => {
        console.log("testCmdInc success", res);
        wx.showToast({
          title: '签到成功',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          ["calendarSignData[" + date + "]"]: date,
          signcount: this.data.signcount + 1,
          calendarSignDay: this.data.signmonth + 1
        })
        db.collection('userinfo').doc(_id).get({
          success: function (res) {
            var userInfo = res.data
            wx.setStorageSync('user', userInfo);
          }
        })
        that.pointsadd("qiandao", '10');
      },
    });

  },

    //提交积分操作表单
    logSubmit: function (e) {
      let that = this,
        data = that.data,
        baby = data.baby,
        content = e.detail.value.content,
        score = +e.detail.value.score
      if (isNaN(score)) score = 0
      if (content.length == 0 || score == 0) {
        wx.showToast({
          title: '请输入内容、积分',
          icon: 'none'
        })
      } else {
        wx.showLoading({
          title: '加载中',
          mask: true
        })
        wx.cloud.callFunction({
          name: 'checkText',
          data: {
            content: content
          }
        }).then(res => {
          if (res.result && res.result.errCode == 0) {
            let time = new Date().getTime()
            if (data.logTab == 'sub') score = 0 - score
            db.collection('logs').add({
              data: {
                baby_id: baby.info[0]._id,
                content: content,
                score: score,
                pic: data.logFormPic,
                deled: false,
                create_time: time
              },
              success: res => {
                wx.hideLoading()
                that.xTap()
                that.loadLog(true)
                db.collection('baby').doc(baby.info[0]._id).get({
                  success: res => {
                    let current = res.data
                    current.score += score
                    wx.cloud.callFunction({
                      name: 'dbUpdate',
                      data: {
                        db_name: 'baby',
                        where: {
                          _id: current._id
                        },
                        update: {
                          score: current.score
                        }
                      }
                    })
                    baby.info[0].score = current.score
                    that.setData({
                      baby: baby
                    })
                  }
                })
                wx.showToast({
                  title: '添加成功',
                  icon: 'success'
                })
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  title: '添加失败',
                  icon: 'none'
                })
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '提交内容含有违法违规内容，请修改后重试',
              icon: 'none'
            })
          }
        }).catch(err => {
          wx.hideLoading()
          wx.showToast({
            title: '提交内容含有违法违规内容，请修改后重试',
            icon: 'none'
          })
        })
      }
    },

  onLoad: function () {
    const that = this;
    var mydate = new Date();
    var year = mydate.getFullYear();
    var month = mydate.getMonth() + 1;
    date = mydate.getDate();
    console.log("date" + date)
    var day = mydate.getDay();
    console.log(day)
    var nbsp;
    if (date <= 7) {
      nbsp = day;
    } else {
      nbsp = 7 - ((date - day) % 7)
    }
    console.log("nbsp" + nbsp);
    var monthDaySize;
    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
      monthDaySize = 31;
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
      monthDaySize = 30;
    } else if (month == 2) {
      // 计算是否是闰年,如果是二月份则是29天
      if ((year - 2000) % 4 == 0) {
        monthDaySize = 29;
      } else {
        monthDaySize = 28;
      }
    };
    var userInfo = app.globalData.userInfo;
    if (date == 1 && userInfo.signmonth == 0) {
      var updatadata = {
        signdata: [],//每月签到日期 
        signmonth: 0//当月签到次数
      };
      var _id = app.globalData.userInfo._id;
      db.collection('userinfo').doc(_id).update({
        data: updatadata,
        success: function (res) {
          //更新成功重置缓存数据
          db.collection('userinfo').doc(_id).get({
            success: function (res) {
              var userInfo = res.data
              wx.setStorageSync('user', userInfo);
              app.globalData.userInfo = userInfo;
              if (!userInfo.signdata) {
                calendarSignData = new Array(monthDaySize);
              } else {
                calendarSignData = new Array(monthDaySize);
                for (var y = 0; y < userInfo.signdata.length; y++) {
                  calendarSignData[userInfo.signdata[y]] = userInfo.signdata[y];
                }
              }
              var _id = app.globalData.userInfo._id;
              that.setData({
                _id: _id,
                calendarSignData: calendarSignData,//当月签到的每天
                signcount: userInfo.signcount,//总计签到加1
                signdata: userInfo.signdata,//当天日期
                calendarSignDay: userInfo.signmonth,//当月签到次数
                signmonth: userInfo.signmonth//当月签到次数 
              })

            }
          })
        },
      })
    } else {
      // 不是1号直接取缓存数据
      if (app.globalData.userInfo) {
        var userInfo = app.globalData.userInfo;
        if (!userInfo.signdata) {
          calendarSignData = new Array(monthDaySize);
        } else {
          calendarSignData = new Array(monthDaySize);
          for (var y = 0; y < userInfo.signdata.length; y++) {
            calendarSignData[userInfo.signdata[y]] = userInfo.signdata[y];
          }
        }
        var _id = app.globalData.userInfo._id;
        this.setData({
          _id: _id,
          calendarSignData: calendarSignData,//当月签到的每天
          signcount: userInfo.signcount == null ? 0 : userInfo.signcount,//总计签到加1
          signdata: userInfo.signdata == null ? 0 : userInfo.signdata,//当天日期
          calendarSignDay: userInfo.signmonth == null ? 0 : userInfo.signmonth,//当月签到次数
          signmonth: userInfo.signmonth == null ? 0 : userInfo.signmonth//当月签到次数 
        })
      }
    }
    this.setData({
      year: year,
      month: month,
      nbsp: nbsp,
      monthDaySize: monthDaySize,
      date: date,
      calendarSignData: calendarSignData,
      calendarSignDay: calendarSignDay
    })
  },
  /**
   * 增加积分
   * @param {} Type 
   * @param {*} qty 
   */
  pointsadd: function (Type, qty) {
    var openid = app.globalData.userInfo._id;
    var date = com.nowTime();
    console.log("增加积分" + openid + "--" + app.globalData.userInfo._id);
    wx.cloud.callFunction({
      name: 'points',
      data: {
        $url: 'points/manage/add',
        Type: Type,
        UserId: openid,
        createTime: date,//创建时间
        updateTime: date//修改时间
      },
      success(res) {
        console.log("success", res);
        wx.showToast({
          title: '积分+' + qty,
        });
      },
      fail(res) {
        console.log("fail", res)
      },
      complete(res) {
        console.log("complete", res)
      }
    })
  },
  bindGetUserInfo: function (e) {
    console.log(e.detail.userInfo);
    if (e.detail.userInfo) {
      const db = wx.cloud.database();
      db.collection('userinfo').where({
        _openid: wx.getStorageSync('openid')
      }).get({
        success: res => {
          if (res.data.length > 0) {
            //1.存用户信息到本地存储
            console.log(res.data[0])
            wx.setStorageSync('userInfo', res.data[0])
            //2.存用户信息到全局变量
            var app = getApp();
            app.globalData.userInfo = res.data[0]

            wx.setStorageSync('isLogin', true);
            wx.navigateBack({
              delta: 1
            })
          } else {
            var user = {
              nickName: e.detail.userInfo.nickName,
              avatarUrl: e.detail.userInfo.avatarUrl,
              province: e.detail.userInfo.province,
              city: e.detail.userInfo.city,
              openid: wx.getStorageSync('openid'),
              gender: e.detail.userInfo.gender
            }
            //授权成功后，跳转进入小程序首页
            const db = wx.cloud.database();
            db.collection('userinfo').add({
              // data 字段表示需新增的 JSON 数据
              data: user
            }).then(res => {
              wx.setStorageSync('isLogin', true);
              console.log(res)
              wx.navigateBack({
                delta: 1
              })
            })
          }
        },
        fail: err => {
          wx.setStorageSync('isLogin', false);
          console.log('[数据库] [查询记录] 失败：')
        }
      })
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '简历信息授权后方可查看!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  }
})

